import json
import os
import sys
import time
import pandas as pd
import requests

import logger_util

# 环境设置
requests.packages.urllib3.disable_warnings()  # 关闭https请求的不安全警告
request_sess = requests.Session()
# 报错requests.exceptions.ProxyError: HTTPSConnectionPool(host='www.xxx.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.
os.environ['NO_PROXY'] = 'sh.rzza.api.hywapp.com'  # 关闭对要访问的域名的代理
logger = logger_util.get_logger()

HEADERS={}
HEADERS_FILE = 'headers.json'
aged_url = 'https://sh.rzza.api.hywapp.com/h5/r/v1/aged'
question_url = 'https://sh.rzza.api.hywapp.com/h5/r/v1/question'
result_url = 'https://sh.rzza.api.hywapp.com/h5/r/v1/aged/review/result'

def send_get(url, param) -> dict:
    logger.debug(f'==>> 请求地址:{url}')
    logger.debug(f'==>> 请求参数:{param}')
    try:
        response = requests.get(url, param)  # 复用session
        total_seconds = response.elapsed.total_seconds()  # 获取实际的响应时间
        logger.debug(f'==>> 请求耗时:{total_seconds}')
    except Exception as e:
        logger.error(f'===>>> 请求异常:{e}')
        return False
    if not response.status_code == 200:
        logger.error(f'===>>> 接口报错1 response:{response.text}')
        return False

    response_json = response.json()
    logger.info(f'==>> 请求结果:{response_json if len(response.text)<2000 else response.text[:600]}')

    return response_json

def send_request(url, param, headers={}) -> dict:
    """
    # 如果返回值为False时，接口自动重试，最多三次
    :param url:
    :param param:
    :param headers:
    :return: False/None/dict
    """
    # reducer_request()
    logger.debug(f'==>> 请求地址:{url}')
    logger.debug(f'==>> 请求参数:{param}')
    if not headers:
        headers = HEADERS
    try:
        response = request_sess.post(url, param, verify=False)  # 复用session
        total_seconds = response.elapsed.total_seconds()  # 获取实际的响应时间
        logger.debug(f'==>> 请求耗时:{total_seconds}')
    except Exception as e:
        logger.error(f'===>>> 请求异常:{e}')
        return False
    if not response.status_code == 200:
        logger.error(f'===>>> 接口报错1 response:{response.text}')
        return False

    response_json = response.json()
    logger.info(f'==>> 请求结果:{response_json if len(response.text)<2000 else response.text[:600]}')

    return response_json


def base_path(path):
    """
    根据运行环境和文件相对路径获取文件绝对路径
    :param path: 文件相对路径
    :return: 文件绝对路径
    """
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        bundle_dir = sys._MEIPASS
    else:
        bundle_dir = os.path.dirname(os.path.abspath(__file__))
    target_path = os.path.join(bundle_dir, path)
    logger.info(f'==>> 目标路径:{target_path}')
    return target_path


def init():
    global HEADERS
    with open(base_path(HEADERS_FILE), 'r', encoding='utf-8') as file:
        HEADERS = json.load(file)


def aged_assess(aged_param):
    if not aged_param:
        aged_param = {
            "birthday": "1961-01-01",
            "age": 62,
            "name": "3269",
            "sex": 0,
            "area_code": "310101",
            "street": "瑞金二路街道",
            "committee": "11",
            "address": "11",
            "phone": "15122335566",
            "id_card": "1234",
            "education": "初中",
            "occupation": "公务员",
            "organization_code": "2022052",
            "member_code": "000",
            "attribute": "机构"
        }
    aged_response = send_request(aged_url, aged_param)
    if aged_response:
        aged_id = aged_response.get("data").get("aged_id")
        print(aged_id)

    # question_1_param = {"origin_no":1}
    # question_1_response = send_get(question_url, question_1_param) # 获取题目

    question_1_result_param = {"aged_id":aged_id,"question_type":6,"origin_no":1,"fill_answer":None,"option_nos":None}
    question_1_result_response = send_request(question_url, question_1_result_param) # 回答题目
    # time.sleep(10)

    question_2_result_param = {"aged_id":aged_id,"question_type":5,"origin_no":2,"fill_answer":"2023;11;17","option_nos":None}
    question_2_result_response = send_request(question_url, question_2_result_param) # 回答题目
    # time.sleep(10)

    question_3_result_param = {"aged_id":aged_id,"question_type":1,"origin_no":3,"fill_answer":None,"option_nos":[1]}
    # question_3_result_response = send_request(question_url, question_3_result_param) # 回答题目
    question_3_result_response = requests.post(question_url,json=question_3_result_param,headers=HEADERS)
    print(question_3_result_response.json())
    # time.sleep(10)

    question_4_result_param = {"aged_id":aged_id,"question_type":4,"origin_no":4,"fill_answer":"花门米","option_nos":None}
    question_4_result_response = send_request(question_url, question_4_result_param) # 回答题目
    # time.sleep(10)

    question_7_result_param = {"aged_id":aged_id,"question_type":1,"origin_no":7,"fill_answer":None,"option_nos":[4]}
    question_7_result_response = requests.post(question_url,json=question_7_result_param,headers=HEADERS)
    print(question_7_result_response.json())
    # time.sleep(10)

    question_8_result_param = {"aged_id":aged_id,"question_type":1,"origin_no":8,"fill_answer":None,"option_nos":[4]}
    question_8_result_response = requests.post(question_url,json=question_8_result_param,headers=HEADERS)
    print(question_8_result_response.json())
    # time.sleep(10)

    question_56_result_param = {"aged_id":aged_id,"question_type":1,"origin_no":56,"option_nos":[2],"fill_answer":None}
    question_56_result_response = requests.post(question_url,json=question_56_result_param,headers=HEADERS)
    print(question_56_result_response.json())
    # question_56_result_response = send_request(question_url, question_56_result_param) # 回答题目
    # time.sleep(10)

    # time.sleep(240)
    result_param = {"aged_id":aged_id}
    result_response = send_get(result_url, result_param) # 提交评测



def load_data():
    books1 = pd.read_excel(r"aged-data.xlsx")
    print(books1)
    data = []
    for idx, row in books1.iterrows():
        row_val = list(row)
        aged_param = {
            "birthday": row_val[9],
            "age": 62,
            "name": row_val[1],
            "sex": 1 if '男' else 0,
            "area_code": "310101",
            "street": row_val[4],
            "committee": row_val[4],
            "address": row_val[4],
            "phone": row_val[10],
            "id_card": row_val[3],
            "education": row_val[5],
            "occupation": row_val[6],
            "organization_code": "2022052",
            "member_code": "000",
            "attribute": "机构"
        }
        # print(row_val)
        # print(json.dumps(aged_param, ensure_ascii=False,))
        data.append(aged_param)
    return data


def main():
    print(111)
    data = load_data()
    for i in range(len(data)):
        aged_assess(data[i]);


if __name__ == "__main__":
    main()